package com.lg.edu.controller;

import com.lg.edu.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserManagementController {

    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/register/{email}/{password}/{code}")
    public String registry(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code) {
        return userService.registry(email, password, code);
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response) {

        String uuid = userService.login(email, password);

        if (StringUtils.isEmpty(uuid)) {
            return "Incorrect user name or password";
        }

        // put the token into cookie
        Cookie cookie = new Cookie("lgToken", uuid);
        response.addCookie(cookie);

        return email;
    }

    @GetMapping("/info/{token}")
    public String getEmailByToken(@PathVariable("token") String token) {
        return userService.getEmailByToken(token);
    }

    @GetMapping("/getValidCodeByEmail/{email}")
    public String getValidCodeByEmail(@PathVariable("email") String email) {
        return userService.getValidCodeByEmail(email);
    }

}
